import { postUserUpdate } from '@/api'

export const inputBirthday = {
  data() {
    return {
      autoUpdate: true,
      rawInput: '',
      formatted: ''
    }
  },
  created() {
  },
  methods: {
    onChangeBirth(event) {
      console.log(event)
      this.rawInput = event.target.value;
      // 处理输入格式
      if (this.formatted.length > this.rawInput.length && this.formatted.charAt(this.formatted.length - 1) === '-') {
        this.rawInput = this.rawInput.slice(0, -1)
      }
      this.formatted = this.rawInput;
      if (this.formatted.length === 4 && /^[0-9]{4}$/.test(this.formatted)) {
        this.formatted += '-';
        // setTimeout(() => {
        //   this.userInfo.birthday = this.formatted
        // })
      }  else if (this.formatted.length === 7 && /^[0-9]{4}-[0-9]{2}$/.test(this.formatted)) {
        this.formatted += '-';
      }
      // 防止删除时候不触发页面更新
      setTimeout(() => {
        this.userInfo.birthday = this.formatted
      console.log(this.formatted, this.userInfo.birthday, this.userInfo, '更新格式化后的输入')

      }, 0)
      // setTimeout(() => {
        // this.userInfo.birthday = this.formatted
      // }, 0)
      // this.$set(this.userInfo, 'birthday', this.formatted)
      // 若输入完整年月日后，进一步处理日期
      if (this.formatted.length === 10 && /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(this.formatted)) {
        var regex = /^(?:202[0-4]|20[01][0-9]|[1-19]\d{3})-(0[1-9]|1[0-2])-(?:0?[1-9]|[12][0-9]|3[01])$/g;
        if (!regex.test(this.userInfo.birthday)) {
          console.log(this.userInfo.birthday)
          uni.showToast({
            title: '请输入正确的日期格式（例如：2000-01-02）',
            icon: 'none',
            duration: 3000
          });
          // 防止删除时候不触发页面更新
          setTimeout(() => {
            this.userInfo.birthday = ''
          }, 0)
          return ''
        }
        if (!this.validateDateString(this.userInfo.birthday)) {
          uni.showToast({
            title: '天数不在合理范围内',
            icon: 'none',
            duration: 3000
          });
          // 防止删除时候不触发页面更新
          setTimeout(() => {
            this.userInfo.birthday = this.userInfo.birthday.slice(0, -2)
          })
          return this.userInfo.birthday.slice(0, -2)
        }
       
        try {
          this.autoUpdate && this.onUpdateUserInfo()
        } catch (error) {
        }
        return this.userInfo.birthday
      } else if (this.formatted.length === 10 && !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(this.formatted)) {
        uni.showToast({
          title: '请输入正确的日期格式（例如：2000-01-02）',
          icon: 'none',
          duration: 3000
        });
        // 防止删除时候不触发页面更新
        setTimeout(() => {
          this.userInfo.birthday = ''
        }, 0)
        return ''
      }
      return this.formatted
    },
    async onUpdateUserInfo() {
      this.userInfo.birth_day = this.userInfo.birthday
      const { code, data } = await postUserUpdate(this.userInfo)
      if (code === 1000) {
        let info = this.$storage.getStorage('userInfo')
        this.$storage.setStorage('userInfo', { ...info, ...data })
        this.userInfo = data
        console.log(this.userInfo, data, 'shanbao')
        // if (info.nick_name && info.avatar) {
        //   try {
        //     data.astro_id !== '' && this.fnGet(data.astro_id)
        //   } catch (error) {
        //   }
        // }
      }
    },
    validateDateString(birthday) {
      var parts = birthday.split('-');
      var year = parseInt(parts[0], 10);
      var month = parseInt(parts[1], 10);
      var day = parseInt(parts[2], 10);
      // 验证天数是否在范围内
      if (day < 1 || day > this.getMaxDaysInMonth(month, year)) {
        return false;
      }
      return true
    },
    getMaxDaysInMonth(month, year) {
      var date = new Date(year, month - 1, 1);
      // 获取下一个月的第一天，然后减去一天得到当前月份的最后一天
      var lastDay = new Date(new Date(date.setMonth(date.getMonth() + 1)).setHours(-24)).getDate();
      return lastDay;
    }
  }
};